package org.example.wine.boot.service.impl;

import jakarta.annotation.Resource;
import org.example.wine.boot.mapper.UserMapper;
import org.example.wine.boot.pojo.Result;
import org.example.wine.boot.pojo.User;
import org.example.wine.boot.service.UserService;
import org.example.wine.boot.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public Result register(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            userMapper.register(username, password);
            return Result.success();
        } else {
            return Result.error("用户名已被占用");
        }
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public Result<String> login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (Objects.equals(user.getUsername(), username) && Objects.equals(user.getPassword(), password)) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", user.getUsername());
            claims.put("id", user.getId());
            return Result.success(JwtUtils.createToken(claims));
        }

        return Result.error("用户名或密码不正确");
    }
}
